#include "stdafx.h"
#include "InlineHook.h"
#include "HookDll.h"
#include "..\Common\Common.h"
#include "SimpleMemHook.h"
#include "DataDef.h"

extern bool g_bHooked;
extern CArrayEx<HOOKFUNCDESC,HOOKFUNCDESC&> g_arrHookedFunctions;

//SimpleMemory Hook
typedef LPVOID ( WINAPI *mallocDef)(size_t size);
typedef LPVOID( WINAPI *reallocDef)(LPVOID memblock, size_t size);
typedef VOID ( WINAPI *freeDef)(LPVOID memblock );

static mallocDef pOrgmalloc = 0;
static reallocDef pOrgrealloc = 0;
static freeDef pOrgfree = 0;

 LPVOID WINAPI Mymalloc(size_t size)
{
#ifndef WIN64
	 __asm 
    {
		mov ebx, malloc 
		add ebx,5 
		push [ebp+8]
		push retaddr
		push ebp
		mov ebp,esp
		jmp ebx 
		retaddr:
		add esp, 4

    }
#else
	return 0;
#endif	

}

LPVOID WINAPI Myrealloc(LPVOID memblock, size_t size)
{
	LPVOID pMem = pOrgrealloc(memblock, size);
	if( NULL == pMem)
		return NULL;

	RemoveCallStack(memblock);
	CreateCallStack(pMem, size);
	return pMem;
}

VOID  WINAPI Myfree(LPVOID pMem)
{
	pOrgfree(pMem);
	RemoveCallStack(pMem);
}

const int SIMPLE_MEMORY_FUN_NO = 3;
void SimpleHookMemAlloc()
{
	g_arrHookedFunctions.SetSize( SIMPLE_MEMORY_FUN_NO ); 
    int nIndex = 0;
    
	int verision = 150;
	HMODULE HCrtModule = NULL;
	char dllname[64] = {0};
	char dllnamed[64] = {0};
	for(; verision >= 70; verision-- )
	{
		memset(dllname, 0 , sizeof(dllname));
		memset(dllnamed, 0 , sizeof(dllnamed));
		sprintf(dllname, "msvcr%d.dll", verision);
		sprintf(dllnamed, "msvcr%dd.dll", verision);
		HCrtModule = GetModuleHandle( dllname );
		if(!HCrtModule)
			HCrtModule = GetModuleHandle( dllnamed );
		if(HCrtModule)
			break;
	}

	mallocDef pOrgFun = (mallocDef)GetProcAddress(HCrtModule, "malloc"); 
	if ( pOrgFun != NULL )
    {
		InlineHook(pOrgFun, Mymalloc);
		nIndex++;
	}

	//SET_INLINE_HOOK(malloc, HCrtModule, dllname, Mymalloc);
	//REGISTER_HOOK_EX(malloc, HCrtModule, dllname);
	//REGISTER_HOOK_EX(realloc, HCrtModule, dllname);
	//REGISTER_HOOK(free, HCrtModule, dllname);
   
	//ASSERT( nIndex == SIMPLE_MEMORY_FUN_NO );
    //HookDynamicLoadedFun( nIndex, g_arrHookedFunctions.GetData());
}